<?php

$timezone = ini_get('date.timezone');
!$timezone && ini_set('date.timezone', 'Asia/Shanghai');

$config = [
    'folder'=>'',
    'pharName'=>'licophp.phar',
    'filePath'=>'.',//__DIR__,//.DIRECTORY_SEPARATOR,
    'fileFilter'=>'/\.php$/',///\.php$/',
    'compressType'=>\Phar::BZ2,//1 Phar::GZ,2 Phar::BZ2
    'startFile'=>'index.php',
];
// print_r($config);
// exit;
$readonly = ini_get('phar.readonly');
if ($readonly) {
    die("请设置phar.readonly = 0");
}
/**
 * 打包
 */
function compress($config)
{
    
    if ($config['folder'] && !is_dir($config['folder'])) {
        mkdir($config['folder'], 0755, true);
    }
    $pharPath = $config['pharName'];
    $config['folder'] && $pharPath = $config['folder'].'/'.$pharPath;
   
    try {
        $handler = new \Phar($pharPath, FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME, pathinfo($pharPath, PATHINFO_BASENAME));

        $handler->buildFromDirectory($config['filePath'], $config['fileFilter']);
        
        $handler->compressFiles($config['compressType']);//php7以下可能会产生无法创建临时文件的bug
        $handler->stopBuffering();

        $startFile = $handler->createDefaultStub($config['startFile'], $config['startFile']);
        $handler->setStub($startFile);
    } catch (\PharException $e) {
        echo $e->getMessage();
    }

    echo '打包成功';
}

/**
 * 解包
 */
function uncompress()
{
    $phar = new \Phar('licophp.phar');
    $phar->extractTo('dist'); //提取一份原项目文件
}

compress($config);
// uncompress();

/**
 * 我们可以直接执行licophp.phar文件：
 * php licophp.phar，这个相当于执行入口文件index.php
 * -----
 * 打包成phar后如果脚本里有使用  __dir__ 这些常量的话要把  phar://   替换掉,要不然file_get_content mkdir 等一些函数会报错找不到路径，但是require_once include等是可以用的
 * define('ROOT_PATH', str_replace('phar://', '', dirname(__dir__)));
 */
